# coding =utf-8
# @Author : hjh
# @File : count_word.py
# @SoftWare : PyCharm

import jieba
from collections import Counter
import matplotlib.pyplot as plt
import wordcloud
import regex as re
from PIL import Image
import numpy as np
# import pandas as pd
# import bar_chart_race as bcr




# 统计词频
def get_word_count(textpath, stopwords=None):
    if stopwords is None:
        stopwords = []
    all_words =[]
    print("获取文件内容...")
    for line in open(textpath, encoding='utf-8'):
        line.strip('\n')
        line = re.sub("[A-Za-z0-9\：\·\—\，\。\“ \”]", "", line)  # 去除杂乱字符
        # seg_list = jieba.cut(line, cut_all=False) # 精准模式下割分
        seg_list = jieba.cut_for_search(line) # 搜索引擎模式下割分
        all_words.extend(seg_list)
    c = Counter()
    # print(all_words)
    print("统计词频...")
    for x in all_words:
        if len(x) > 1 and x != '\r\n' and x not in stopwords:  # 长度大于一，并且不为换行等字符
            c[x] += 1
    return c



def main():
    print("生成词云...")
    stop = open('stop_word.txt', 'r+', encoding='utf-8')
    stop_words = stop.read().split("\n") # 筛选词源
    text_file_path = "wordCloud.txt" # 词云源
    font_path = "msyhbd.ttf" # 设置字体
    mask = np.array(Image.open('mask.png'))  # 词云图形状
    counter = get_word_count(text_file_path, stop_words)
    # print(counter)
    word_cloud = wordcloud.WordCloud(
        mask = mask,
        background_color="white",
        scale=3,
        font_path=font_path
    ).generate_from_frequencies(counter)
    # image_colors = wordcloud.ImageColorGenerator(mask)  # 从背景图建立颜色方案
    # word_cloud.recolor(color_func=image_colors)  # 将词云颜色设置为背景图方案
    print("保存图片...")
    word_cloud.to_file("./word_cloud.jpg")  # 将图片输出为文件


    print("生成词频图...")
    plt.rcParams["font.sans-serif"] = ["SimHei"]  # 设置字体
    plt.rcParams["axes.unicode_minus"] = False
    plt.figure(figsize=(12, 6), dpi=100) # 设置绘图区域大小
    plt.title('词频统计')  # 写标题
    plt.xlabel('统计词')
    plt.ylabel('出现次数')
    plt.xticks(rotation=15) # 旋转x轴标签
    sort_counter = sorted(dict(counter).items(),key=lambda s:s[1],reverse = True)
    # print(sort_counter)
    x_name = []
    x_count = []
    for i in sort_counter:
        x_name.append(i[0])
        x_count.append(i[1])
    plt.bar(x_name[:20], x_count[:20])  # 绘制柱状图
    for a,b in zip(x_name[:20],x_count[:20]):
        plt.text(a,b,b,ha='center', va = 'bottom',fontsize=14)# 坐标轴显示
    print("保存图片...")
    plt.savefig('./word_frequency.jpg')
    # plt.show()

    # df = pd.read_csv('./dateBar.csv', index_col=0, encoding='gbk')  # 导入数据
    # bcr.bar_chart_race(df, 'example.gif')



if __name__ == '__main__':
    main()

